var map = null;
var appD;
var extent = [0, 0, 1024, 400];//图片图层四至
var projection = new ol.proj.Projection({//定义坐标系
    code: 'xkcd-image',
    units: 'pixels',
    extent: extent
});
//标记图层
var layerPop;
//信息弹框
var popup;
//闪烁图层
var point_overlay;

var mapLayer;

var userPop;

var helper = {
    init: function (id, url) {
        jsHelper.initMap(url);
        jsHelper.move();
        jsHelper.initLocator(id);
        jsHelper.showPhop();
        jsHelper.addLayer();
    },
    initIndeMap: function (id, url) {
        jsHelper.initMap(url);
        jsHelper.initLocator(id);
        jsHelper.showPhop();
        map.removeInteraction(appD);
    },

    initTrack: function (param) {
        mapList = param;
        mapIndex = 0;
        helper.showTrack(mapList[mapIndex]);
    },

    showTrack: function (item) {
        index = 0;
        date = 0;
        tempDate = 0;
        $("#strId").val(item.strId);
        $("#strName").text(item.strName);
        $("#strName").val(item.strName);
        var url = encodeURI(item.imgUrl);
        //处理坐标
        trackHelper.dealPoints(item.points);
        //初始化地图
        jsHelper.initMap(url);
        if (trackLayer != null) {
            map.removeLayer(trackLayer);
            map.removeLayer(speedLayer);
        }
        trackLayer = new ol.layer.Vector({
            source: new ol.source.Vector(),
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 0, 0, 0.5)'
                }),
                stroke: new ol.style.Stroke({
                    color: 'red',
                    width: 1
                })
            })
        });
        speedLayer = new ol.layer.Vector({
            source: new ol.source.Vector()
        });
        map.addLayer(trackLayer);
        map.addLayer(speedLayer);
        trackHelper.addPolygon();
        $("#tempstop").unbind("click");
        $("#tempstop").click(function () {
            map.render();
            clearInterval(inter);
            if (date != 0) {
                tempDate = (new Date()).getTime();
            }
            ispuse = 1;
        });
        $("#start").unbind("click");
        $("#start").click(function () {
            if (date == 0) {
                date = (new Date()).getTime();
            }
            if (tempDate != 0) {
                date = date + ((new Date()).getTime() - tempDate);
            }
            ispuse = 0;
            trackHelper.startAnimation();
            trackHelper.startMove();
        });
        $("#stop").unbind("click");
        $("#stop").click(function () {
            trackHelper.stopAnimation();
            clearInterval(inter);
        });
        $("#next").unbind("click");
        $("#next").click(function () {
            index = index + 1;
            date = date - speed;
            map.render();
        });
        $("#prev").unbind("click");
        $("#prev").click(function () {
            index = index - 1;
            date = date + speed;
            map.render();
        });
        //自动点击开始按钮
        if (document.all) {
            document.getElementById("start").click();
        }
        // 其它浏览器
        else {
            var e = document.createEvent("MouseEvents");
            e.initEvent("click", true, true);
            document.getElementById("start").dispatchEvent(e);
        }
    }
};

var jsHelper = {
    //初始化地图
    initMap: function (url) {
        if (map == null) {
            map = new ol.Map({
                target: 'map',
                view: new ol.View({
                    projection: projection,
                    center: ol.extent.getCenter(extent),
                    zoom: 2,
                    minZoom: 2,
                    maxZoom: 4
                }),
                interactions: ol.interaction.defaults({
                    pinchRotate: false,
                    doubleClickZoom: false
                })

            });
            map.addControl(new ol.control.ZoomToExtent());
        } else {
            map.removeLayer(mapLayer);
            map.removeLayer(layerPop);
            map.getLayers().forEach(function (value) {
                map.removeLayer(value);
            });
        }
        //如果有闪烁图层，直接移除
        if (point_overlay != null) {
            map.removeOverlay(point_overlay);
        }
        if (popup != null) {
            var element = popup.getElement();
            $(element).popover('destroy');
        }
        //设备图层
        layerPop = new ol.layer.Vector({
            source: new ol.source.Vector()
        });
        mapLayer = new ol.layer.Image({
            source: new ol.source.ImageStatic({
                url: url,//地址
                projection: projection,
                imageExtent: extent
            })
        });
        map.addLayer(mapLayer);
        map.addLayer(layerPop);
    },


    //初始化地图上的标注
    initLocator: function (strId) {
        var requestData = {
            strId: strId,
        };
        $.ajax({
            url: "/resident/room/strId",//请求路径
            type: "post",//请求方式
            data: requestData,//请求参数
            success: function (apiResult) {
                if (apiResult.resultCode === 2000) {
                    $.each(apiResult.data, function (index, item) {
                        jsHelper.showAnchor(item)
                    })
                }
            }, error: function () {

            },
            dataType: "json" //服务器响应的数据格式

        })
    },
    //展示图标
    showAnchor: function (item) {
        var x = item.longitude - 0;
        var y = item.latitude - 0;
        var anchor = new ol.Feature({
            geometry: new ol.geom.Point([x, y])
        });
        // 设置样式,不同设备类型用不同的icon，在样式中就可以设置图标
        var iconPath = path + '/resource/map/icon/homeIcon.png';
        anchor.setStyle(new ol.style.Style({
            image: new ol.style.Icon({
                src: iconPath,
                anchor: [0.5, 0.5],
                crossOrigin: 'anonymous',
                size: [30, 30]
            }),

        }));
        anchor.setId(item.no);
        anchor.setProperties({
            roomId: item.roomId,
            roomName: item.roomName,
            equNo: item.equNo,
            describe: item.describe
        });
        // 添加到之前的创建的layer中去
        layerPop.getSource().addFeature(anchor);
    },
    //展示图标的详细信息
    showPhop: function () {
        popup = new ol.Overlay({
            element: document.getElementById('popup'),
            //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
            autoPan: true
        });
        map.addOverlay(popup);
        popup.setPositioning("bottom-center");
        map.on('click', function (evt) {
            var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
                return feature;
            });
            if (feature) {
                var attr = feature.getProperties();
                var content = '<p>房间信息：</p>' +
                    '<code>房间名称：' + attr.roomName + '</code><br>' +
                    '<code>绑定设备名称：' + attr.equNo + '</code><br>' +
                    '<code>描述：' + attr.describe + '</code><br>' +
                    '<code style="float: right"><button onclick="addConcealPointHelper.deleteConcealPoint(' + attr.roomId + ')">删除</button></code>';
                var element = popup.getElement();
                var coordinate = evt.coordinate;
                $(element).popover('destroy');
                popup.setPosition(coordinate);
                $(element).popover({
                    placement: 'top',
                    animation: false,
                    html: true,
                    content: content
                });
                $(element).popover('show');
            } else {
                var element = popup.getElement();
                $(element).popover('destroy');
            }

        });
    },

    random: function () {
        var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
        var num = Math.random() * 5 * plusOrMinus;
        return num;
    },
    //拖动图标
    move: function () {
        var app = {};
        /**
         * @constructor
         * @extends {ol.interaction.Pointer}
         */
        app.Drag = function () {
            ol.interaction.Pointer.call(this, {
                handleDownEvent: app.Drag.prototype.handleDownEvent,
                handleDragEvent: app.Drag.prototype.handleDragEvent,
                handleMoveEvent: app.Drag.prototype.handleMoveEvent,
                handleUpEvent: app.Drag.prototype.handleUpEvent
            });
            this.coordinate_ = null;
            this.cursor_ = 'pointer';
            this.feature_ = null;
            this.previousCursor_ = undefined;

        };
        ol.inherits(app.Drag, ol.interaction.Pointer);
        app.Drag.prototype.handleDownEvent = function (evt) {
            var map = evt.map;
            var feature = map.forEachFeatureAtPixel(evt.pixel,
                function (feature) {
                    return feature;
                });
            if (feature) {
                this.coordinate_ = evt.coordinate;
                this.feature_ = feature;
            }

            return !!feature;
        };
        app.Drag.prototype.handleDragEvent = function (evt) {
            var deltaX = evt.coordinate[0] - this.coordinate_[0];
            var deltaY = evt.coordinate[1] - this.coordinate_[1];

            var geometry = this.feature_.getGeometry();
            geometry.translate(deltaX, deltaY);
            this.coordinate_[0] = evt.coordinate[0];
            this.coordinate_[1] = evt.coordinate[1];
            //console.log(this);
        };
        app.Drag.prototype.handleMoveEvent = function (evt) {
            if (this.cursor_) {
                var map = evt.map;
                var feature = map.forEachFeatureAtPixel(evt.pixel,
                    function (feature) {
                        return feature;
                    });
                var element = evt.map.getTargetElement();
                if (feature) {
                    if (element.style.cursor != this.cursor_) {
                        this.previousCursor_ = element.style.cursor;
                        element.style.cursor = this.cursor_;
                    }
                } else if (this.previousCursor_ !== undefined) {
                    element.style.cursor = this.previousCursor_;
                    this.previousCursor_ = undefined;
                }
            }
        };
        app.Drag.prototype.handleUpEvent = function () {
            var address = $("#strName").val();
            var requestData = {
                roomId: this.feature_.get("roomId"),
                structureId: $("#strId").val(),
                longitude: this.coordinate_[0],
                latitude: this.coordinate_[1],
                address: address
            };
            $.ajax({
                url: "/resident/save/room",//请求路径
                type: "post",//请求方式
                data: requestData,//请求参数
                success: function (apiResult) {

                }, error: function () {

                },
                dataType: "json" //服务器响应的数据格式

            });

            this.coordinate_ = null;
            this.feature_ = null;
            return false;
        };
        appD = new app.Drag();
        map.addInteraction(appD);
    },
    //添加图标
    addLayer: function () {
        map.on('click', function (evt) {
            var no = $("#selectNo").val();
            var address = $("#strName").val();
            if (no != null && no != "") {
                //保存位置
                var requestData = {
                    no: no,
                    structureId: $("#strId").val(),
                    longitude: evt.coordinate[0],
                    latitude: evt.coordinate[1],
                    address: address
                };
                $.ajax({
                    url: "/equipment/save/location",//请求路径
                    type: "post",//请求方式
                    data: requestData,//请求参数
                    success: function (apiResult) {
                        //如果保存成功，添加图层
                        jsHelper.showAnchor(apiResult.data);
                        //将selectNo至空
                        $("#selectNo").val("");
                        //将对应的地址直接修改
                        $("#" + no + "_address").text(address);
                        //将图片变回鼠标
                        var url = encodeURI(path + "/resource/img/a1.jpg");
                        document.body.style.cursor = "url(" + url + ") 12 12,default";

                    }, error: function () {

                    },
                    dataType: "json" //服务器响应的数据格式
                });
            }
        });

    },

};
